package com.baiyi.cloud.platform.utils;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;

import com.baiyi.cloud.platform.model.system.LoginAppUser;



/**
 * 
  * @ClassName: SysUserUtil
  * @Description: 获取用户信息
  * @author huwenfeng
  * @date 2019年1月7日
  *
 */
public class SysUserUtil {

	/**
	 * 
	* @Title: getLoginAppUser
	* @Description: 获取登陆的 LoginAppUser
	* @param @return    参数
	* @return LoginAppUser    返回类型
	* @throws
	 */
	@SuppressWarnings("rawtypes")
	public static LoginAppUser getLoginAppUser() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		if (authentication instanceof OAuth2Authentication) {
			OAuth2Authentication oAuth2Auth = (OAuth2Authentication) authentication;
			authentication = oAuth2Auth.getUserAuthentication();

			if (authentication instanceof UsernamePasswordAuthenticationToken) {
				UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
			
				return (LoginAppUser) authenticationToken.getPrincipal();
			}else if (authentication instanceof PreAuthenticatedAuthenticationToken ){
				//刷新token方式
				PreAuthenticatedAuthenticationToken authenticationToken = (PreAuthenticatedAuthenticationToken) authentication;
				return (LoginAppUser) authenticationToken.getPrincipal();
				
			}
		}

		return null;
	}
}
